﻿using mozhi.smarterp.BasicData.Enums;
using mozhi.smarterp.BasicData.Events;
using System;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace mozhi.smarterp.BasicData.Organizations
{
    public class Organization : AuditedAggregateRoot<Guid>, IMultiTenant
    {
        public Guid? TenantId { get; private set; }

        public DateTime? ActivatedDate { get; private set; }

        public AccountingStandardType AccountingStandard { get; private set; }

        public string OfficialName { private set; get; }

        public string Name { private set; get; }

        /// <summary>
        /// 本位币
        /// </summary>
        public Guid? StandardCurrencyId { private set; get; }

        public string TaxIDNumber { private set; get; }

        /// <summary>
        /// 完成初始化
        /// </summary>
        public bool Initialized {  get; private set; }

        private Organization() { }


        public Organization(Guid id, string name, string officialName, string taxIDNumber,AccountingStandardType standardType, DateTime? activationDate, Guid? currencyId)
        {
            Id = id;
            Name = name;
            OfficialName = officialName;
            TaxIDNumber = taxIDNumber;
            AccountingStandard = standardType;
            ActivatedDate = activationDate;
            StandardCurrencyId = currencyId;

            Validate();
        }

        public void Change(string officialName, string taxIdNumber, Guid? standardCurrencyId, AccountingStandardType accountingStandard, DateTime? activatedDate)
        {
            OfficialName = officialName;
            TaxIDNumber = taxIdNumber;
            StandardCurrencyId = standardCurrencyId;
            ActivatedDate = activatedDate;
            AccountingStandard = accountingStandard;

            Validate();

            AddDistributedEvent(new AccountingStandardChangeEvent()
            {
                AccountingStandardType = accountingStandard,
                TenantId = TenantId,
            });

        }

        #region
        private void Validate()
        {
            if (OfficialName.IsNullOrEmpty())
                throw new UserFriendlyException("法定名称为必填项", "100000");

            if (Name.IsNullOrEmpty())
                throw new UserFriendlyException("显示名称为必填项", "100000");

            if (AccountingStandard == default)
                throw new UserFriendlyException("会计准则为必填项", "100000");

            if (ActivatedDate == null)
                throw new UserFriendlyException("启用日期为必填项", "100000");

            if (StandardCurrencyId == null)
                throw new UserFriendlyException("本位币为必填项", "100000");
        }
        #endregion
    }
}
